#Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
import sys
import os
import subprocess


class BsCppOpPytonGenerator():
    op_type = "relu7"
    target_dir = "./opdir"
    curr_dir = ""
    template_dir = ""
    clear_func_table = []
    clear_func_depth = []

    def __init__(self: any, op_type: str, op_dir: str) -> None:
        self.op_type = op_type
        self.curr_dir = os.getcwd()
        self.template_dir = os.path.abspath(sys.argv[0] + '/../../op_template')
        self.target_dir = os.path.abspath(op_dir)

        cmd1 = f"find {self.template_dir} -maxdepth 1 -mindepth 1 ! -wholename '{self.template_dir}'"
        cmd2 = f"xargs -i cp -r {{}} {self.target_dir}"
        p1 = subprocess.Popen(cmd1.strip().split(' '), stdout=subprocess.PIPE)
        p2 = subprocess.Popen(cmd2.strip().split(' '), stdin=p1.stdout)
        p2.wait(10)
        p1.stdout.close()
        if p2.returncode != 0:
            print(f"[ERROR]: {cmd1} | {cmd2}")
            sys.exit(1)


    def run(self):
        for filepath, dirnames, filenames in os.walk(self.target_dir):
            for file_name in filenames:
                new_name = file_name.replace('relu7', self.op_type.lower())
                old_name = os.path.join(filepath, file_name)
                new_name = os.path.join(filepath, new_name)

                cmd = "sed -i s/relu7/" + self.op_type.lower() + "/g " + old_name
                ret = subprocess.run(cmd.strip().split(' '))
                if ret.returncode != 0:
                    print("ERROR: ", ret)
                    sys.exit(1)
                cmd = "sed -i s/Relu7/" + self.op_type + "/g " + old_name
                ret = subprocess.run(cmd.strip().split(' '))
                if ret.returncode != 0:
                    print("ERROR: ", ret)
                    sys.exit(1)
                cmd = "sed -i s/RELU7/" + self.op_type.upper() + "/g " + old_name
                ret = subprocess.run(cmd.strip().split(' '))
                if ret.returncode != 0:
                    print("ERROR: ", ret)
                    sys.exit(1)

                os.rename(old_name, new_name)


def main():
    if len(sys.argv) != 3:
        raise RuntimeError("arguments must be 2: python bscpp_op_generator.py [op_type] [op_dir]")
    try:
        op_type = sys.argv[1]
        op_dir = sys.argv[2]
    except:
        raise RuntimeError("error input: python bscpp_op_generator.py [op_type] [op_dir]")
    if os.path.exists(op_dir):
        raise RuntimeError("op project dir {} already exist".format(op_dir))
    os.makedirs(op_dir)
    generator = BsCppOpPytonGenerator(op_type, op_dir)
    generator.run()
    print("generate operation directory: {}".format(op_dir))


if __name__ == "__main__":
    main()